package cn.yr.file.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.yr.common.exception.ret.Ret;
import cn.yr.oss.OssKit;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 文件上传
 *
 * @author Lang 1102076808@qq.com
 * @date 2021-04-08 22:56
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/file")
public class FileController {

	@Value("${oss.base-disc}")
	private String baseDisc;

	@Resource
	private OssKit ossKit;

	@RequestMapping("/upload")
	public Ret upload(MultipartFile file){
		System.out.println(file.getSize());
		long maxSize = 10*1024*1024;
		if(file.getSize()>maxSize){
			return Ret.error("文件不能大于10M");
		}
		try {
			if(StrUtil.isEmpty(file.getOriginalFilename())){
				return Ret.error("文件名不能为空");
			}
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			Snowflake snowflake = IdUtil.createSnowflake(1, 1);
			long id = snowflake.nextId();
			String imgName = baseDisc+"/"+id+suffix;
			String upload = ossKit.upload(file.getBytes(), imgName);
			return Ret.success(MapUtil.builder("img",upload).map());
		}catch (Exception e){
			return Ret.error(e.getMessage());
		}
	}


}
